package actions;

import net.sf.json.JSONObject;
import utils.DBSelect;
import utils.DBSelectInt;
import utils.JSONResponse;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UsersAction extends CMActionSupport{

	private String id;
	private String usernumber;
	private String Realname;
	private String email;
	private String role;
	private String password;



	public String list() {
		JSONObject result = new JSONObject();
		final List<JSONObject> jsonList = new ArrayList<>();
		String sql = "select * from user"; //查看所有用户

		new DBSelect(sql).exec(new DBSelectInt() {

			@Override
			public boolean deal(ResultSet rs) throws SQLException {
				while (rs.next()) {
					JSONObject tmpJson = new JSONObject();
					tmpJson.put("usernumber",rs.getString("id"));
					tmpJson.put("realname",rs.getString("name"));
					int role = rs.getInt("level");
					String jurisdiction;
					switch (role) {
						case 1:
							jurisdiction="普通用户";
							break;
						case 2:
							jurisdiction="普通管理员";
							break;
						case 3:
							jurisdiction="高级管理员";
							break;
						default:jurisdiction="读取出错";
					}
					tmpJson.put("jurisdiction",jurisdiction);
					jsonList.add(tmpJson);
				}
				return false;
			}
		});
		result.put("data",jsonList);
		JSONResponse.returnJsonToResponse(result);
		return NONE;
	}

	public String add() {
		String level = "0";
		if (role.equals("用户")){
			level = "1";
		}
		else if (role.equals("普通管理员")){
			level = "2";
		}
		else if (role.equals("高级管理员")){
			level = "3";
		}
		String sql = "insert user(id,name,password,level) values('"+usernumber+"','"+Realname+"','"+password+"','"+level+"');";
		new DBSelect(sql).exec(new DBSelectInt() {

			@Override
			public boolean deal(ResultSet rs) throws SQLException {
				return false;
			}
		});
		return NONE;
	}

	public String del() {
		String sql = "delete from  user where id='"+usernumber+"'";
		new DBSelect(sql).exec(new DBSelectInt() {

			@Override
			public boolean deal(ResultSet rs) throws SQLException {
				return false;
			}
		});
		JSONObject result = new JSONObject();
		result.put("status","success");
		JSONResponse.returnJsonToResponse(result);
		return NONE;
	}
	
	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUsernumber() {
		return usernumber;
	}

	public void setUsernumber(String usernumber) {
		this.usernumber = usernumber;
	}

	public String getRealname() {
		return Realname;
	}

	public void setRealname(String realname) {
		Realname = realname;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}
